package com.gec.component;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author Str
 * @Date 2021/10/18 16:52
 * @Description :HttpServletResponse的实现类
 */
public class HttpServletResponseWapper extends HttpServletResponse {
    private OutputStream os;
    HttpServletResponseWapper(OutputStream os){
        this.os = os;
    }
    //{2}包装响应头部。。
    private String packResponse(
            String mime, long size ){
        return "HTTP/1.1 200 OK\r\n"+
                "Content-Type: "+ mime +"\r\n"+
                "Last-Modified: Tue, 03 Apr 2018 08:30:09 GMT\r\n"+
                "Accept-Ranges: bytes\r\n"+
                "ETag: \"2a4416fa25cbd31:0\"\r\n"+
                "Server: My_SERVER1.0\r\n"+
                "Date: Mon, 18 Oct 2021 10:39:27 GMT\r\n"+
                "Content-Length: "+ size +"\r\n\r\n";
    }
    @Override
    public void flush(){
        //{1}获取输出器。
        byte[] data = getWriter().getData();
        //{2}包装响应头部。
        String header = packResponse( mime, data.length );
        //{3}通过 os 输出出去。
        try{
            //{4}先输出响应头..
            os.write( header.getBytes() );
            //{5}再输出响应体..
            os.write( data );
        }catch(IOException e){
            e.printStackTrace();
            //----------不处理-----------
        }
    }
}
